<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>基础表单</title>
    <link rel="stylesheet" href="__LIBS__/layui/css/layui.css" />
    <link rel="stylesheet" href="__MODULE__/admin.css?v=317" />
    <link rel="stylesheet" href="__JS__/plugins/wx-audio/wx-audio.css" ><!--音频播放器组件-->
    <link rel="stylesheet" href="__JS__/plugins/webuploader/webuploader.css?v=1.0.1" ><!--webUploader上传组件-->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
        #formBasForm {
            max-width: 1000px;
            margin: 30px 50px;
        }

        .layui-form-item {
            display: flex ;
        }

        .layui-form-label {
            flex: 3;
        }

        .layui-input-block {
            flex: 14;
        }

        .layui-input-block {
            margin-left: 20px !important;
            min-height: 36px;
        }

        #formBasForm .layui-form-item {
            margin-bottom: 25px;
        }
        .file-input{
            position: relative;
            display: inline-block;
            cursor: pointer;
            background: #00b7ee;
            padding: 10px 15px;
            color: #fff;
            text-align: center;
            border-radius: 3px;
            overflow: hidden;
        }
    </style>
</head>

<body>
<!-- 加载动画 -->
<div class="page-loading">
    <div class="ball-loader">
        <span></span><span></span><span></span><span></span>
    </div>
</div>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <ul class="layui-tab-title" style="margin-bottom: 20px;">
            <li><a ew-href="{:url('index')}" ew-title="课程管理">课程管理</a></li>
            <li><a ew-href="{:url('add_menu')}" ew-title="添加目录">添加目录</a></li>
            <li  class="layui-this"><a href="javascript:location.reload();">添加课程</a></li>
            <li><a ew-href="{:url('add_files')}" ew-title="添加课件">添加课件</a></li>
            <li><a ew-href="{:url('deleted_menus')}" ew-title="回收站">回收站</a></li>
        </ul>
        <div class="layui-card-body">
            <!-- 表单开始 -->
            <form class="layui-form" id="formBasForm" lay-filter="formBasForm">
                <input type="hidden" name="id" value="{$item['id']?$item['id']:''}">
                <input type="hidden" name="menumedia" value="{$menuinfo['media']?$menuinfo['media']:''}">
                <input type="hidden" name="sonmedia" value="{$item['media']?$item['media']:''}">
                <input type="hidden" name="upload_area" value="{isset($upload_area)?$upload_area:''}">
                <input type="hidden" name="menuid" value="{$menuinfo['id']?$menuinfo['id']:''}">

                <div class="layui-form-item">
                    <label class="layui-form-label layui-form-required">选择目录:</label>
                    <div class="layui-input-block">
                        <select name="menuid" lay-verify="" lay-filter="selectmenu" lay-skin="select">
                            <option value="">请选择课程目录</option>
                            {if $menuinfo}
                            {foreach name="menus" item="vo"}
                            <option value="{$vo.id}" {$vo.id==$menuinfo['id']?'selected':''}>{$vo.menuname}</option>
                            {/foreach}
                            {else /}
                            {foreach name="menus" item="vo"}
                            <option value="{$vo.id}" >{$vo.menuname}</option>
                            {/foreach}
                            {/if}
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label layui-form-required">课程名称:</label>
                    <div class="layui-input-block">
                        <input name="coursename" class="layui-input" value="{$item['coursename']?$item['coursename']:''}" required lay-verify="required"/>
                    </div>
                </div>
                {if $menuinfo}
                {if $menuinfo['media']=='all'}
                <div class="layui-form-item">
                    <label class="layui-form-label layui-form-required">课程类型:</label>
                    <div class="layui-input-block">
                        <select name="media" lay-verify="" lay-filter="selectmedia" lay-skin="select">
                            <option value="">请选择课程类型</option>
                            {if $item}
                            {foreach name="medias" item="vo"}
                            <option value="{$vo.val}" {$vo.val==$item['media']?'selected':''}>{$vo.medianame}</option>
                            {/foreach}
                            {else /}
                            {foreach name="medias" item="vo"}
                            <option value="{$vo.val}">{$vo.medianame}</option>
                            {/foreach}
                            {/if}
                        </select>
                    </div>
                </div>
                {/if}
                {/if}

                {if $item}
                <div class="layui-form-item audio-upload" style="display: none;">
                    <label class="layui-form-label layui-form-required">上传音频：</label>
                    <input type="hidden" name="audio_src" id="lay-music" lay-verify="music" value="{$item['src']?$item['src']:''}" >
                    <div class="layui-upload layui-input-block">
                        <div id="lay-music-upload"><i class="layui-icon">&#xe6fc;</i> 上传音频</div>
                        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                            预览音频：
                            <div class="layui-upload-list" id="lay-music-list">
                            </div>
                        </blockquote>
                    </div>
                </div>
                {else /}
                <div class="layui-form-item audio-upload" style="display: none;">
                    <label class="layui-form-label layui-form-required">上传音频：</label>
                    <input type="hidden" name="audio_src" id="lay-music" lay-verify="music" >
                    <div class="layui-upload layui-input-block">
                        <div id="lay-music-upload"><i class="layui-icon">&#xe6fc;</i> 上传音频</div>
                        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                            预览音频：
                            <div class="layui-upload-list" id="lay-music-list">
                            </div>
                        </blockquote>
                    </div>
                </div>
                {/if}
                {if $item}
                <div class="layui-form-item videosrc video-upload" >
                    <label class="layui-form-label layui-form-required">视频链接：</label>
                    <div class="layui-input-block">
                        <input name="video_src" class="layui-input inline-block" value="{$item['src'] ? to_media_url($item['src']):''}" placeholder="请输入视频链接地址,支持MP4、Ogg、WebM格式"/>
                    </div>
                </div>
                {else /}
                <div class="layui-form-item video-upload" style="display: none;">
                    <label class="layui-form-label layui-form-required">视频上传模式:</label>
                    <div class="layui-input-block">
                        {if $item}
                        <input type="radio" name="upload_mode" lay-filter="upload_mode" value="0" title="直接上传" {if $item['upload_mode']=='0' }checked="checked"{/if}>
                        <input type="radio" name="upload_mode" lay-filter="upload_mode" value="1" title="填写链接" {if $item['upload_mode']=='1' }checked="checked"{/if}>
                        {else /}
                        <input type="radio" name="upload_mode" lay-filter="upload_mode" value="0" title="直接上传">
                        <input type="radio" name="upload_mode" lay-filter="upload_mode" value="1" title="填写链接">
                        {/if}
                    </div>
                </div>
                <div class="layui-form-item videosrc" style="display: none;">
                    <label class="layui-form-label layui-form-required">视频链接：</label>
                    <div class="layui-input-block">
                        <input name="video_src" class="layui-input inline-block" value="{$item['src']?$item['src']:''}" placeholder="请输入视频链接地址,支持MP4、Ogg、WebM格式"/>
                    </div>
                </div>
                {if $upload_area == 0}
                <!--webupload上传视频到本地-->
                <div class="layui-form-item videoupload" style="display: none;">
                    <label class="layui-form-label layui-form-required">上传视频到本地服务器：</label>
                    <input type="hidden" name="video_src1" id="lay-video" lay-verify="video">
                    <div class="layui-upload layui-input-block">
                        <div id="lay-upload2"><i class="layui-icon">&#xe6ed;</i> 上传视频</div>
                        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                            预览视频：
                            <div class="layui-upload-list" id="lay-video-list">
                            </div>
                        </blockquote>
                    </div>
                </div>
                {else/}
                <!--七牛上传视频-->
                <div class="layui-form-item videoupload2" style="display: none;">
                    <label class="layui-form-label layui-form-required">上传视频到对象存储空间：</label>
                    <input type="hidden" name="video_src1" id="lay-video2" lay-verify="video" >
                    <div class="layui-upload layui-input-block">
                        <input class="file-input" type="file" id="lay-upload3" accept="video/mp4,video/ogg,video/webM" value="<i class='layui-icon'>&#xe6ed;</i> 上传视频" />
                        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                            预览视频：
                            <div class="layui-upload-list" id="lay-video-list2">
                            </div>
                            <div class="layui-upload-list hidden" id="lay-video-list3">
                            </div>
                        </blockquote>
                    </div>
                </div>
                {/if}
                {/if}
                <div class="layui-form-item">
                    <label class="layui-form-label">单课程价格: </label>
                    <div class="layui-input-block">
                        <input name="price" class="layui-input inline-block" style="width: 160px;" value="{$item['price']?$item['price']:0}" /><span>&nbsp;&nbsp;元</span>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">是否支持试看:</label>
                    <div class="layui-input-block">
                        {if $item}
                        <input type="radio" name="is_sk" lay-filter="is_sk" value="0" title="不支持" {if $item['is_sk']=='0' }checked="checked"{/if}>
                        <input type="radio" name="is_sk" lay-filter="is_sk" value="1" title="支持" {if $item['is_sk']=='1' }checked="checked"{/if}>
                        {else /}
                        <input type="radio" name="is_sk" lay-filter="is_sk" value="0" title="不支持" checked="checked">
                        <input type="radio" name="is_sk" lay-filter="is_sk" value="1" title="支持">
                        {/if}
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">试看时长: </label>
                    <div class="layui-input-block">
                        <input name="freesecond" class="layui-input inline-block" style="width: 160px;" value="{$item['freesecond']?$item['freesecond']:0}"/><span>&nbsp;&nbsp;秒</span>
                    </div>
                </div>
                <div class="layui-form-item tuwen-detail" style="display: none;">
                    <label class="layui-form-label layui-form-required">图文详情: </label>
                    <div class="layui-input-block">
                        <textarea name="introduce" id="LAY_editor2" >{$item['introduce']?$item['introduce']:''}</textarea>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block" style="display: flex;
                    justify-content: space-around;
                ">
                        <button id="btnDemoEdtGetContent" class="layui-btn" lay-filter="formBasSubmit" lay-submit>&emsp;提交&emsp;</button>
                        <button type="reset" class="layui-btn layui-btn-primary">&emsp;重置&emsp;</button>
                    </div>
                </div>
            </form>
            <!-- //表单结束 -->
        </div>
    </div>
</div>

<!-- js部分 -->
<script type="text/javascript" src="__LIBS__/layui/layui.js"></script>
<script type="text/javascript" src="__NJS__/common.js?v=317"></script>
<script type="text/javascript" src="__LIBS__/tinymce/tinymce.min.js"></script>
<script src="__LIBS__/jquery/jquery-3.2.1.min.js"></script>
<script src="__JS__/plugins/wx-audio/wx-audio.js" ></script><!--音频播放器组件-->
<script src="__JS__/plugins/webuploader/webuploader.js"></script><!--webUploader上传组件-->
<script src="__JS__/plugins/qiniu/qiniu.min.js"></script>
<script src="__JS__/plugins/ali/aliyun-oss-sdk.min.js"></script>
<script src="__JS__/plugins/tencent/cos-js-sdk-v5.min.js"></script>
<script src="__JS__/plugins/ueditor/ueditor.config.js" ></script><!--百度富文本-->
<script src="__JS__/plugins/ueditor/ueditor.all.js" ></script><!--百度富文本-->
<script>
    //百度富文本编辑器
    var editor = UE.getEditor('LAY_editor2', {
        initialFrameWidth:780,
        initialFrameHeight:450,
        autoHeight: false,
        autoHeightEnabled:false,
        autoFloatEnabled:false
    });
    //自定义上传接口
    UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
    UE.Editor.prototype.getActionUrl = function(action) {
        if (action == 'uploadimage' || action == 'uploadscrawl') {
            return '/index.php/admin/upload/ueditorUpload';//这就是自定义的上传地址
        } else {
            return this._bkGetActionUrl.call(this, action);
        }
    }
    var upload_area = "{$upload_area?$upload_area:'0'}";
    var qiniuzone = "{$qiniu['zone']?$qiniu['zone']:''}";
    var qiniu_domain = "{$qiniu['domain']?$qiniu['domain']:''}";
    window.media = "{$menuinfo['media']?$menuinfo['media']:''}";
    window.sonmedia = '';
    console.log(qiniuzone,qiniu_domain,window.media);
    var isupload = false;
    var ischange = false;
    var rooturl = "{:request()->root(true)}";
    layui.use(['layer', 'form', 'laydate','jquery','cascader','upload','admin','element','tableSelect'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var laydate = layui.laydate;
        var cascader = layui.cascader;
        var upload = layui.upload;
        var admin = layui.admin;
        var element = layui.element
        $(function(){
            let media=$("input[name='menumedia']").val();
            let sonmedia=$("input[name='sonmedia']").val();
            // let media=select_media?select_media:menumedia;
            console.log(media);
            if(media=='video'){
                $(".video-upload").show();
                $(".audio-upload").hide();
                $(".tuwen-detail").hide();
            }else if(media=='audio'){
                $(".video-upload").hide();
                $(".audio-upload").show();
                $(".tuwen-detail").hide();
            }else if(media=='tuwen'){
                $(".video-upload").hide();
                $(".audio-upload").hide();
                $(".tuwen-detail").show();
            }else if(media=='all'){
                if(sonmedia=='video'){
                    $(".video-upload").show();
                    $(".audio-upload").hide();
                    $(".tuwen-detail").hide();
                }else if(sonmedia=='audio'){
                    $(".video-upload").hide();
                    $(".audio-upload").show();
                    $(".tuwen-detail").hide();
                }else if(sonmedia=='tuwen'){
                    $(".video-upload").hide();
                    $(".audio-upload").hide();
                    $(".tuwen-detail").show();
                }
            }
            if($("input[name='audio_src']").val()!=''){
                //预览音频实现播放
                var wxAudio = new WxAudio({
                    ele: '#lay-music-list',
                    title: "{$item['coursename']?$item['coursename']:''}",
                    disc: '',
                    src: "{$item['src']?$item['src']:''}",
                    width: '320px',
                    autoplay: false,
                    loop: false,
                    currentTime:0,//从多少秒开始播放
                    ended: function () {
                        console.log('播放结束');
                    }
                });
            }
        });

        /*音频上传*/
        var uploaderMusic = WebUploader.create({
            auto: true,// 选完文件后，是否自动上传。
            server: "{:url('admin/upload/upload')}",// 文件接收服务端。
            duplicate :true,// 重复上传文件，true为可重复false为不可重复
            // chunked: true,// 分片上传大文件
            pick: {
                id: "#lay-music-upload",// 选择文件的按钮
                multiple: false,//true多文件上传 false单文件上传
            },
            fileSingleSizeLimit: 1000*1024*1024, //限制上传单个文件大小，单位是B，1M=1024000B
            accept: {
                title: 'Audio',
                extensions: 'mp3',
                mimeTypes: '.mp3'
            },
            //上传成功
            'onUploadSuccess': function(file, data, response) {
                let src = data._raw?data._raw:data;
                $("#lay-music").val(src);
                $("#" + file.id).show();
                /**************音频播放器***************/
                var wxAudio = new WxAudio({
                    ele: '#'+ file.id,//dom元素
                    title: file.name,//文件名
                    disc: '',//描述
                    src: src,//音频地址
                    width: '320px',//进度条
                    loop: false,//循环播放 bool值
                    currentTime:0,//从多少秒开始播放
                    ended: function () {}//播放完执行，loop为true不执行
                });
                /**************音频播放器***************/
                $( '#'+file.id ).next('p').html('<span style="color: #009688;">上传成功!</span>');
            },
            //上传失败
            'uploadError':function(file){
                $( '#'+file.id ).next('p').html('<span style="color: #FF5722;">上传失败!</span>');
            }
        });
        // //上传进度
        // uploaderMusic.on( 'uploadProgress' ,function(file,percentage){
        //     element.progress('lay-music', Math.round(100 * percentage)+'%');
        // });
        //音频加入队列
        uploaderMusic.on( 'fileQueued', function( file ) {
            $('#lay-music-list').html('<div id="' + file.id + '" style="margin: 0 10px 10px 0;display:none;"></div><p id="lay-msg">正在上传... <i class="layui-icon layui-icon-loading-1 layui-icon layui-anim layui-anim-rotate layui-anim-loop"></i></p>')
        });
        //错误信息提示
        uploaderMusic.on('error', function (code) {
            switch (code) {
                case 'F_EXCEED_SIZE':
                    layer.msg('音频大小不得超过'+  uploaderMusic.options.fileSingleSizeLimit/1024/1024 + 'MB',{icon:2,time:1500,shade:0.1});
                    break;
                case 'Q_TYPE_DENIED':
                    layer.msg('请上传正确的音频格式',{icon:2,time:1500,shade:0.1});
                    break;
                default:
                    layer.msg('上传错误，请刷新',{icon:2,time:1500,shade:0.1});
                    break;
            }
        });

        // 上传视频到本地
        var uploader = WebUploader.create({
            auto: true,// 选完文件后，是否自动上传。
            server: "{:url('admin/upload/video')}",// 文件接收服务端。
            duplicate :true,// 重复上传文件，true为可重复false为不可重复
            chunked: true,// 分片上传大文件
            pick: {
                id: "#lay-upload2",// 选择文件的按钮
                multiple: false,//true多文件上传 false单文件上传
            },
            fileSingleSizeLimit: 1000*1024*1024, //限制上传单个文件大小，单位是B，1M=1024000B
            accept: {
                title: 'Video',
                extensions: 'mp4',
                mimeTypes: '.mp4'
            },
            //上传成功
            'onUploadSuccess': function(file, data, response) {
                // console.log(file);
                // console.log(data);
                // console.log(response);
                $("#lay-video").val(rooturl+ '/' + data.filePath);
                layui.config({
                    base: '/src/' //静态资源所在路径
                }).extend({
                    ckplayer: 'modules/ckplayer'
                }).use(['ckplayer'], function() {
                    var ckplayer = layui.ckplayer
                    var videoObject = {
                        container: '#' + file.id,
                        loop: false,
                        autoplay: false,
                        video: [
                            [rooturl+ '/' + data.filePath, 'video/mp4']
                        ]
                    };
                    var player = new ckplayer(videoObject);
                })
                $( '#'+file.id ).show();
                $( '#'+file.id ).next('div').hide();
                $( '#'+file.id ).next().next('p').html('<span style="color: #009688;">上传成功!</span>');
                isupload = true;
                ischange = true;
            },
            //上传失败
            'uploadError':function(file){
                $( '#'+file.id ).next('div').hide();
                $( '#'+file.id ).next().next('p').html('<span style="color: #FF5722;">上传失败!</span>');
            }
        });
        //上传进度
        uploader.on( 'uploadProgress' ,function(file,percentage){
            element.progress('lay-video', Math.round(100 * percentage)+'%');
        });
        //视频加入队列
        uploader.on( 'fileQueued', function( file ) {
            $('#lay-video-list').html('<div id="' + file.id + '" style="width: 80%;height: auto;display:none;"></div><div class="layui-progress layui-progress-big" lay-showpercent="true" lay-filter="lay-video"><div class="layui-progress-bar" lay-percent="0%"></div></div><p id="lay-msg">正在上传... <i class="layui-icon layui-icon-loading-1 layui-icon layui-anim layui-anim-rotate layui-anim-loop"></i></p>')
        });
        //错误信息提示
        uploader.on('error', function (code) {
            switch (code) {
                case 'F_EXCEED_SIZE':
                    layer.msg('视频大小不得超过'+  uploader.options.fileSingleSizeLimit/1024/1024 + 'MB',{icon:2,time:1500,shade:0.1});
                    break;
                case 'Q_TYPE_DENIED':
                    layer.msg('请上传正确的视频格式',{icon:2,time:1500,shade:0.1});
                    break;
                default:
                    layer.msg('上传错误，请刷新',{icon:2,time:1500,shade:0.1});
                    break;
            }
        });
        var zone = qiniuzone;
        $("#lay-upload3").change(function(){
            $("#lay-video-list2").html(
                "<div class='layui-progress layui-progress-big' lay-showpercent='true' lay-filter='lay-video2'>"+
                "<div class='layui-progress-bar' lay-percent='0%' style='width: 9%;'></div>"+
                "</div>"+
                "<p id='lay-msg2'>正在上传... "+
                "<i class='layui-icon layui-icon-loading-1 layui-icon layui-anim layui-anim-rotate layui-anim-loop'></i>"+
                "</p>"
            );
            let file = this.files[0];
            let key = file.name;
            //js获取文件文件名去掉后缀名
            var filename = file.name.substring(0, file.name.lastIndexOf("."));
            console.log('文件名称：',filename);
            $("input[name='coursename']").val(filename);
            if(upload_area == 1){

                if(zone == '' || zone == undefined || !zone){
                    layer.alert('请先设置七牛存储空间！');
                    return false;
                }
            }
            $.ajax({
                url: "{:url('admin/upload/uptoken')}",
                data: {
                    fileName: key
                },
                success: (res) => {
                    if(upload_area == 1) {
                        let token = res.uptoken;
                        var region;
                        if(zone == 'z0'){
                            region = qiniu.region.z0
                        }else if(zone == 'z1'){
                            region = qiniu.region.z1
                        }else if(zone == 'z2'){
                            region = qiniu.region.z2
                        }
                        let key = res.key;
                        let config = {
                            useCdnDomain: true,
                            region: region
                        };
                        let putExtra = {
                            fname: "",
                            params: {},
                            mimeType: null
                        };
                        const observer = {
                            next: (res) => {
                                let total = res.total;
                                element.progress('lay-video2', Math.round(total.percent)+'%');
                            },
                            error: (err) => {
                                console.log(err);
                                $("#lay-msg3").text('处理失败：' + err.message);
                            },
                            complete(res) {
                                $("#lay-video2").val(qiniu_domain+ res.key);
                                $("#lay-msg2").text('上传成功！');
                                isupload = true;
                                //转码
                                $.ajax({
                                    url: "{:url('admin/upload/persistentFops')}",
                                    data: {
                                        filename: res.key,
                                    },
                                    success: (res1) => {
                                        console.log(res1);
                                        $("#lay-video-list3").html(
                                            "<div class='layui-progress layui-progress-big' lay-showpercent='true' lay-filter='lay-video3'>"+
                                            "<div class='layui-progress-bar' lay-percent='0%' style='width: 9%;'></div>"+
                                            "</div>"+
                                            "<p id='lay-msg3'>准备转码... "+
                                            "<i class='layui-icon layui-icon-loading-1 layui-icon layui-anim layui-anim-rotate layui-anim-loop'></i>"+
                                            "</p>"+
                                            "<p id='m3u8_src' style='display: none;'>"+
                                            "</p>"
                                        ).removeClass('hidden');
                                        if(res1.code == 0) {
                                            element.progress('lay-video3', '2%');
                                            var num = 0;
                                            var timer = setInterval(function (){
                                                $.ajax({
                                                    url: "{:url('admin/upload/queryPersistentFopStatus')}",
                                                    data: {
                                                        id: res1.msg,
                                                    },
                                                    success: (res2) => {
                                                        if(res2.code == 0) {
                                                            if(res2.msg.code == 0) {
                                                                $("#lay-video2").val(res2.url + res2.msg.items[0].key);
                                                                $("#m3u8_src").show();
                                                                $("#m3u8_src").text('转码文件地址：'+res2.url + res2.msg.items[0].key);
                                                                $("#lay-msg3").html('<span style="color:#FF5722;">恭喜您,转码已经完成！</span>'+ "<i style='color:#FF5722;' class='layui-icon layui-icon-ok'></i>");
                                                                clearInterval(timer);
                                                                element.progress('lay-video3', '100%');
                                                                ischange = true;
                                                            }else if(res2.msg.code == 3){
                                                                layer.alert("转码失败！请检查文件格式或文件是否已损坏");
                                                                $("#lay-msg3").html('<span style="color:#FFB800;">转码失败！请检查文件格式或文件是否已损坏</span>'+ "<i style='color:#FFB800;' class='layui-icon layui-icon-close'></i>");
                                                                clearInterval(timer);
                                                                element.progress('lay-video3', '0%');
                                                            }
                                                            else {
                                                                num++
                                                                if(num <= 4) {
                                                                    element.progress('lay-video3', num * 15 + '%');
                                                                } else {
                                                                    if(num < 36) {
                                                                        element.progress('lay-video3', 60 + num + '%');
                                                                    }
                                                                }
                                                                if(res2.msg.code == 1){
                                                                    $("#lay-msg3").html('等待加入队列...' +"<i class='layui-icon layui-icon-loading layui-icon layui-anim layui-anim-rotate layui-anim-loop'></i>");
                                                                }else if(res2.msg.code == 2){
                                                                    $("#lay-msg3").html('正在转码中...' +"<i class='layui-icon layui-icon-loading layui-icon layui-anim layui-anim-rotate layui-anim-loop'></i>");
                                                                }
                                                            }
                                                        } else {
                                                            clearInterval(timer);
                                                            $("#lay-msg3").text('转码失败：' + res2.msg.desc);
                                                        }
                                                    }
                                                })
                                            }, 5000);
                                        }
                                    }
                                })

                            }
                        }
                        let subscription;
                        // 调用sdk上传接口获得相应的observable，控制上传和暂停
                        let observable = qiniu.upload(file, key, token, putExtra, config);
                        observable.subscribe(observer)
                    } else if(upload_area == 2) {
                        //aliyun oss
                        if(res[0] == -1) {
                            $("#lay-msg2").text('上传失败！错误信息：' + res[1]);
                            return;
                        }
                        let client = new OSS({
                            // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
                            region: 'oss-cn-hangzhou',
                            // 从STS服务获取的临时访问凭证。临时访问凭证包括临时访问密钥（AccessKeyId和AccessKeySecret）和安全令牌（SecurityToken）。
                            accessKeyId: res.accessKeyId,
                            accessKeySecret: res.accessKeySecret,
                            stsToken: res.SecurityToken,
                            // 填写Bucket名称。
                            bucket: res.bucket
                        });
                        async function multipartUpload () {
                            try {
                                // 填写Object完整路径和本地文件的完整路径。Object完整路径中不能包含Bucket名称。
                                // 您可以通过自定义文件名（例如exampleobject.txt）或目录（例如mytestdoc/exampleobject.txt）的形式，实现将文件上传到当前Bucket或Bucket中的指定目录。
                                // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
                                let result = await client.multipartUpload(res.key, file, {
                                    progress: function (p, checkpoint) {
                                        element.progress('lay-video2', Math.round(p * 100)+'%');
                                        if(p == 1) {
                                            isupload = true;
                                            ischange = true;
                                            $("#lay-msg2").text('上传成功！');
                                            $("#lay-video2").val(res.accessUrl);

                                            //转码
                                            $.ajax({
                                                url: "{:url('admin/upload/persistentFops')}",
                                                data: {
                                                    // 'z0.01z002ccgs1nw4c8yq00muocmp0002t4'
                                                    filename: res.accessUrl,
                                                },
                                                success: (res1) => {
                                                    console.log(res1);
                                                    $("#lay-video-list3").html(
                                                        "<div class='layui-progress layui-progress-big' lay-showpercent='true' lay-filter='lay-video3'>"+
                                                        "<div class='layui-progress-bar' lay-percent='0%' style='width: 9%;'></div>"+
                                                        "</div>"+
                                                        "<p id='lay-msg3'>正在转码... "+
                                                        "<i class='layui-icon layui-icon-loading-1 layui-icon layui-anim layui-anim-rotate layui-anim-loop'></i>"+
                                                        "</p>"
                                                    ).removeClass('hidden');
                                                    if(res1.code == 0) {
                                                        $("#lay-msg2").text('正在转码...');
                                                        element.progress('lay-video3', '2%');
                                                        var num = 0;
                                                        var timer = setInterval(function (){
                                                            $.ajax({
                                                                url: "{:url('admin/upload/queryPersistentFopStatus')}",
                                                                data: {
                                                                    id: res1.msg,
                                                                },
                                                                success: (res2) => {
                                                                    console.log(res2);
                                                                    if(res2.code == 0) {
                                                                        if(res2.msg.code == 0) {
                                                                            $("#lay-video2").val(res2.url + res2.msg.items);
                                                                            $("#lay-msg3").text('转码完成！');
                                                                            clearInterval(timer);
                                                                            element.progress('lay-video3', '100%');
                                                                            ischange = true;
                                                                        } else {
                                                                            num++
                                                                            if(num <= 4) {
                                                                                element.progress('lay-video3', num * 15 + '%');
                                                                            } else {
                                                                                if(num < 36) {
                                                                                    element.progress('lay-video3', 60 + num + '%');
                                                                                }
                                                                            }
                                                                        }
                                                                    } else {
                                                                        clearInterval(timer);
                                                                        $("#lay-msg3").text('转码失败：' + res2.msg.desc);
                                                                    }
                                                                }
                                                            })
                                                        }, 5000);
                                                    }
                                                }
                                            })
                                        }
                                        // 断点记录点。浏览器重启后无法直接继续上传，您需要手动触发上传操作。
                                        tempCheckpoint = checkpoint;
                                    },
                                    // meta: { year: 2020, people: 'test' },
                                    // mime: 'text/plain'
                                })
                            } catch(e){
                                $("#lay-msg2").text('上传失败！');
                            }
                        }

                        // 开始分片上传。
                        multipartUpload();
                    }
                }

            })
        });

        form.on('radio(upload_mode)', function(data){
            // var upload_area = "{$upload_area}"
            console.log('存储类型为'+upload_area)
            let mode = data.value
            if (mode == '0') {
                if(upload_area == 0){
                    $('.videoupload').show();
                    $('.videoupload2').hide();
                }else {
                    $('.videoupload').hide();
                    $('.videoupload2').show();
                }
                // $('.videoupload2').show();
                $('.videosrc').hide();
            }
            else if (mode == '1') {
                $('.videoupload').hide();
                $('.videosrc').show();
                $('.videoupload2').hide();
            }
        });

        form.on('select(selectmenu)', function(res){
            console.log(res)
            let menuid=res.value;
            window.open("{:url('add_course')}?menuid="+menuid,'_self');
        });
        form.on('select(selectmedia)', function(res){
            let media=window.sonmedia=res.value;
            var menumedia=$("input[name='menumedia']").val();
            var menuid=$("input[name='menuid']").val();
            if(menumedia=='all'){
                window.open("{:url('add_course')}?menuid="+menuid+'&media='+media,'_self');
            }else{
                if(media=='video'){
                    $(".video-upload").show();
                    $(".audio-upload").hide();
                    $(".tuwen-detail").hide();
                }else if(media=='audio'){
                    $(".video-upload").hide();
                    $(".audio-upload").show();
                    $(".tuwen-detail").hide();
                }else if(media=='tuwen'){
                    $(".video-upload").hide();
                    $(".audio-upload").hide();
                    $(".tuwen-detail").show();
                }
            }
        });
        /* 监听表单提交 */
        form.on('submit(formBasSubmit)', function (data) {
            let upload_mode=$("input[name='upload_mode']:checked").val();
            console.log(upload_mode);
            if(window.media =='video'){
                if($("input[name='video_src']").val() == ''){
                    if(upload_mode == '' || !upload_mode || upload_mode == 'undefined'){
                        layer.alert('请先选择视频上传模式！');
                        return false;
                    }else if(upload_mode == 0){
                        if(!isupload) {
                            layer.alert('请等待视频上传完成');
                            return false;
                        }
                        if(!ischange && upload_area !=0) {
                            layer.alert('请等待视频转码完成');
                            return false;
                        }
                    }
                }
            }else if(window.media =='all'){
                if(window.sonmedia == ''){
                    layer.alert('请先选择课程类型并上传课程！');
                    return false;
                }else if(window.sonmedia =='video'){
                    if(upload_mode == '' || !upload_mode || upload_mode == 'undefined'){
                        layer.alert('请先选择视频上传模式！');
                        return false;
                    }else if(upload_mode == 0){
                        if(!isupload) {
                            layer.alert('请等待视频上传完成');
                            return false;
                        }
                        if(!ischange && upload_area !=0) {
                            layer.alert('请等待视频转码完成');
                            return false;
                        }
                    }
                }
            }
            $('.layui-btn').addClass('layui-disabled').attr('disabled','disabled');
            $.ajax({
                url:"{:url('add_course')}",
                type:'post',
                dataType:'json',
                data:data.field,
                success:function(res){
                    //console.log(res)
                    if (res.code == 0) {
                        layer.msg(res.msg,{icon:1,time:1500,shade:0.1})
                    } else {
                        $(".layui-btn").removeClass('layui-disabled').removeAttr('disabled');
                        wk.error(res.msg);
                        return false;
                    }
                }
            })
        });

    });
</script>
</body>

</html>